import axios from 'axios';
import Nprogress from 'nprogress';
import { get } from '@/utils/localStorage';

// 请求基地址
const baseURL = 'https://consult-api.itheima.net';

// 创建axios实例
const request = axios.create({
  baseURL,
  timeout: 10000,
});

// 请求拦截器
request.interceptors.request.use((config) => {
  Nprogress.start();
  const loginInfo = get();
  if (loginInfo) {
    config.headers.Authorization = `Bearer ${loginInfo.token}`;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use((response) => {
  Nprogress.done();
  if (response.data.code !== 10000) {
    return Promise.reject(new Error(response.data.message));
  }
  return response.data;
}, (error) => {
  Nprogress.done();
  return Promise.reject(error);
});


export default request;